package jade.oo.core.behaviours;

import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.oo.core.behaviours.state.BehaviourState;
import jade.oo.core.behaviours.state.BehaviourStillActive;
import jade.oo.core.behaviours.state.BehaviourWaitingForMessage;

import java.io.Serializable;

public class MessageReceiverBehaviour<T extends Serializable> implements
		Behaviour {

	private final Inbox inbox;
	private final MessageReceiver<T> messageReceiver;
	private final MessageTemplate messageTemplate;

	public MessageReceiverBehaviour(Inbox inbox,
			MessageReceiver<T> messageReceiver, MessageTemplate messageTemplate) {
		this.inbox = inbox;
		this.messageReceiver = messageReceiver;
		this.messageTemplate = messageTemplate;
	}

	@Override
	public BehaviourState action() {
		ACLMessage message = inbox.receive(messageTemplate);
		if (message != null) {
			T messageBody;
			try {
				messageBody = (T) message.getContentObject();
			} catch (UnreadableException e) {
				throw new RuntimeException(e);
			}
			AID sender = message.getSender();

			messageReceiver.receive(messageBody, sender);
			return new BehaviourStillActive();
		} else {
			return new BehaviourWaitingForMessage();
		}
	}

	@Override
	public int onEnd() {
		return 0;
	}

	@Override
	public void onStart() {

	}

}
